from django.core.paginator import Paginator
from django.db import IntegrityError
from django.db.models import ProtectedError
from django.shortcuts import render

from utils import responsedata
from utils.customerutils import CustomerUtils
from utils.responsestatus import ResponseStatus
from .models import Course


# Create your views here.

# 课程分页
def course_page(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        course_list = Course.objects.all().order_by('-id')
        paginator = Paginator(course_list, form_data.get('size', 5))
        total = paginator.count
        # 当前页数据
        current_page = paginator.page(form_data.get('page', 1))
        table_data = list(current_page.object_list.values())
        response = {
            'code': ResponseStatus.BUSINESS_SUCCESS,
            'data': {
                'total': total,
                'tableData': table_data
            }
        }
        return CustomerUtils.response_json(response)

def course_remove(request, id):
    try:
        Course.objects.filter(id=id).delete()
        return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)
    except ProtectedError as e:
        response = responsedata.BUSINESS_ERROR_DATA
        response['message'] = "课程被占用，不能删除！"
        return CustomerUtils.response_json(response)

def course_insert_edit(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        id = form_data.get('id')
        try:
            # 新增
            if id is None:
                Course(**form_data).save()
            # 修改
            Course.objects.filter(id=id).update(**form_data)
        except IntegrityError as e:
            # 想让错误提示更细致
            result = responsedata.BUSINESS_ERROR_DATA
            result['message'] = str(e)
            return CustomerUtils.response_json(result)
        else:
            return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)


def course_one(request, id):
    course = Course.objects.filter(id=id).values().first()
    response = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'course': course
        }
    }
    return CustomerUtils.response_json(response)


def course_list(request):
    course_list = Course.objects.all()
    courses = []
    for course in course_list:
        courses.append({
            'id': course.id,
            'course_name': course.course_name,
        })
    resp = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'courseList': courses
        }
    }
    return CustomerUtils.response_json(resp)